package com.dating.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dating.entities.AsyntaskDating;
import com.dating.libs.android.view.FlowLayout;
import com.dating.libs.client.parttern.doit.OnTaskListener;
import com.dating.libs.web.services.datingservice.DatingService;
import com.dating.libs.web.services.datingservice.UserProperties;
import com.dating.pref.Constant;
import com.dating.pref.Function;
import com.dating.view.DtTextView;

public class UserInfo extends Activity implements OnClickListener {
	public static final String TAG = "UserInfo";
	int userID=-1;
	boolean cancel = false;
	static Toast t;
	Handler mHandler;
	Dialog d;
	ArrayList<DtTextView> mArrayProperties;

	// View
	TextView tvName, tvAddress, tvAge, tvGender, tvMore, tvEdit1, tvEdit2;
	ImageView imAvatar;
	Spinner spIntend;
	FlowLayout flProperties;

	// LISTENER
	AsyntaskDating mAsynInfo;
	OnTaskListener mInfoMeListener;
	AsyntaskDating mAsynLikes;
	OnTaskListener mLikesListener;
	AsyntaskDating mAsynAvatar;
	OnTaskListener mUpdateAvatarListener;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.user_info);

		// Initial Variable
		t = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mHandler = new Handler();
		d = new Dialog(this);
		mAsynInfo = new AsyntaskDating();
		mAsynLikes = new AsyntaskDating();
		mAsynAvatar=new AsyntaskDating();
		mArrayProperties=new ArrayList<DtTextView>();

		// Get View
		findIdView();
		Bundle b=this.getIntent().getExtras();
		if(b!=null && b.containsKey("user_id")){
			userID=b.getInt("user_id");
		}else{
			// default
		}
		// Listener
		registListeners();

		new Thread(new Runnable() {

			@Override
			public void run() {
				requestUserData();
			}
		}).start();
		
		imAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(userID>-1){
					Intent i=new Intent(UserInfo.this, ShowImage.class);
					Bundle b=new Bundle();
					b.putInt("user_id", userID);
					i.putExtras(b);
					startActivity(i);
				}
			}
		});
	}

	// Listener
	private void registListeners() {
		tvEdit1.setOnClickListener(this);
		
		mInfoMeListener = new OnTaskListener() {
			DatingService dating = new DatingService();

			@Override
			public void onPrepare(String... values) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						UserInfo.this.showDialog(Constant.DIALOG_LOADING);
					}
				});

				onDoBackground(values);
			}

			@Override
			public void onDoBackground(String... params) {
				try {
					ArrayList<UserProperties> _t = dating
							.getAllUserProperties(Integer
									.parseInt(Dating.ME.UID));
					if (_t.size() > 0) {
						Dating.ME.mMeProperties = _t;
					}

					onComplete(true);
				} catch (NullPointerException e) {
					showToast("Not user info");
					onComplete(false);
				} catch (Exception e) {
					e.printStackTrace();
					onComplete(false);
				}
			}

			@Override
			public void onComplete(Boolean values) {
				mHandler.post(new Runnable() {
					public void run() {
						if(d.isShowing())
							UserInfo.this.dismissDialog(Constant.DIALOG_LOADING);
					}
				});

				if (values) {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							updateUI();
						}
					});
				}

			}
		};
		// get Likes facebook Listener
		mLikesListener = new OnTaskListener() {

			@Override
			public void onPrepare(String... values) {
				onDoBackground();
			}

			@Override
			public void onDoBackground(String... params) {
				onComplete(true);
			}

			@Override
			public void onComplete(Boolean values) {
				if (values) {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							StringBuilder _str = new StringBuilder();
							_str.append(Dating.ME.likes);
							showToast(_str.toString());
							DtTextView tv_likes = new DtTextView(UserInfo.this);
							tv_likes.setText(_str.toString());
							flProperties.addView(tv_likes);
						}
					});
				}
			}
		};
		mUpdateAvatarListener = new OnTaskListener() {
			String url = "http://anh.24h.com.vn/upload/1-2011/images/2011-02-22/1298362370-CHUNG-HAN-DONG--3-.jpg";
			Bitmap bmp=null;
			@Override
			public void onPrepare(String... params) {
				
			}

			@Override
			public void onDoBackground(String... params) {
				if(params.length>1)
					if(params[0].equals("updateavatar"))	//String command
//						if(!params[1].equals(null) && !params[1].equals(""))
							url=params[1];
				Log.e("loading url", url);
				// set avatar
				try {
					
					bmp = Function.getBitmapFromUrl(new URL(url));
					if (bmp != null)
						onComplete(true);
					else
						onComplete(false);
				} catch (MalformedURLException e) {
					e.printStackTrace();
					onComplete(false);
				}
			}

			@Override
			public void onComplete(final Boolean values) {
				Log.e("update avatar", "complete");
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						if(values && bmp!=null){
							Dating.ME._bmp=bmp;
							imAvatar.setImageBitmap(bmp);
						}else
							imAvatar.setImageResource(R.drawable.noavatar);
					}
				});
				
			}
		};
		mAsynInfo.setOnTaskListener(mInfoMeListener);
		mAsynLikes.setOnTaskListener(mLikesListener);
		mAsynAvatar.setOnTaskListener(mUpdateAvatarListener);
	}

	// SUPER
	private void findIdView() {
		tvAge = (TextView) findViewById(R.id.tv_age);
		tvName = (TextView) findViewById(R.id.tv_name);
		tvAddress = (TextView) findViewById(R.id.tv_address);
		tvGender = (TextView) findViewById(R.id.tv_gender);

		tvMore = (TextView) findViewById(R.id.tv_more);
		tvEdit1 = (TextView) findViewById(R.id.tv_edit1);
		tvEdit2 = (TextView) findViewById(R.id.tv_edit2);

		imAvatar = (ImageView) findViewById(R.id.im_avatar);

		spIntend = (Spinner) findViewById(R.id.sp_intend);

		flProperties = (FlowLayout) findViewById(R.id.fl_properties);
	}

	private void requestUserData() {
		if(Dating.ME._bmp!=null)
			imAvatar.setImageBitmap(Dating.ME._bmp);
		// get user info
		mAsynInfo.run(Dating.ME.UID);

		// get likes
		mAsynLikes.execute(Dating.ME.UID);

		// get avatar
		showToast(Dating.ME._link_image);
		mAsynAvatar.execute("updateavatar",Dating.ME._link_image);
	}
	private void updateUI() {
//		Log.e("ME", Dating.ME.toString());
		// name age
		if (!Dating.ME._fullname.equals("0"))
			tvName.setText(Dating.ME._fullname);
		if (!Dating.ME._address.equals("0"))
			tvAddress.setText(Dating.ME._address);
		if (!Dating.ME._birthday.equals("0"))
			tvAge.setText(Dating.ME._birthday);
		if (!Dating.ME._gender.equals("0"))
			tvGender.setText(Dating.ME._gender);

		// User infomation
		if (Dating.ME.mMeProperties.size() > 0) {
			flProperties.removeAllViews();
			for (UserProperties _i : Dating.ME.mMeProperties) {
				if (_i.getName("").equals("Age")) {
					tvAge.setText("Age: " + _i.getValue(""));
				}
				if (!_i.getValue("").equals("")) {
					DtTextView _t = new DtTextView(this);
					
					_t.setProperties(_i.getName(""));
					_t.setText(_i.getValue(""));
					
					flProperties.addView(_t);
					mArrayProperties.add(_t);
				}
			}
		}

		// likes

	}
//	Bundle bundle=new Bundle();
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case Constant.DIALOG_EDIT:
			
			break;

		default:
			break;
		}
		
		return d;
	}
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case Constant.DIALOG_LOADING:
			d=new Dialog(this);
			d.requestWindowFeature(Window.FEATURE_NO_TITLE);
			d.setCancelable(true);
			d.setContentView(R.layout.loading);
			d.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel = true;
				}
			});
			// d.setTitle("Loging in...");
			cancel = false;
			d.show();
			break;
		
		default:
			break;
		}
		return d;
	}

	public static void showToast(String text) {
		if (t != null) {
			t.cancel();
		}
		t.setText(text);
		t.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	@Override
	protected void onResume() {
		updateUI();
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_edit1:
			Log.e("Edit info", "OK");
			startActivity(new Intent(this,EditInfo.class));
			
			break;

		default:
			break;
		}
	}
}
